<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" inline>
      <el-form-item label="场馆/场地名称">
        <el-input v-model="queryParams.keyWord" placeholder="请输入场馆名" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <!-- <div class="mb-4">
      <el-button
        v-hasPermi="['sys:site:btn_add']"
        type="primary"
        @click="handleAdd"
        >新增</el-button
      >
    </div> -->

    <!-- 数据表格 -->
    <el-table :data="list" v-loading="loading" :tree-props="{ children: 'children' }" row-key="id">
      <el-table-column prop="stadiumName" label="场馆名称" />
      <el-table-column prop="type" label="场地类型">
        <template #default="{ row }">
          {{
            (dict?.type?.site_type?.find((item: any) => item.value === row.type) || {}).label ||
            '未知类型'
          }}
        </template>
      </el-table-column>

      <el-table-column prop="siteName" label="场地名称" />

      <el-table-column prop="enable" label="状态">
        <template #default="{ row }">
          <el-tag v-if="row.children == null" :type="row.enable ? 'primary' : 'warning'">
            {{ row.enable ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="approval" label="审批状态" width="130">
        <template #default="{ row }">
          <el-tag
            v-if="row.children == null"
            :type="row.approval == '1' ? 'success' : row.approval == '2' ? 'danger' : 'warning'"
          >
            {{ { '0': '待审批', '1': '通过', '2': '驳回' }[row.approval as string] || '未知状态' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="updateTime" label="更新时间" />
      <!-- <el-table-column label="操作" width="auto">
        <template #default="{ row }">
          <el-button
            v-if="row.children != null"
            type="text"
            v-hasPermi="['sys:site:btn_open_update']"
            @click="batchToggleStatus(row, 1)"
          >
            批量启用
          </el-button>
          <el-button
            v-if="row.children != null"
            type="text"
            v-hasPermi="['sys:site:btn_open_update']"
            @click="batchToggleStatus(row, 0)"
          >
            批量停用
          </el-button>

          <el-button
            v-if="row.children == null"
            type="text"
            v-hasPermi="['sys:site:btn_open_update']"
            :style="{ color: row.enable ? '#F56C6C' : '#67C23A' }"
            @click="toggleStatus(row)"
          >
            {{ row.enable ? "停用" : "启用" }}
          </el-button>
          <el-button
            v-if="row.children == null"
            type="text"
            v-hasPermi="['sys:site:btn_update']"
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-if="row.children == null && row.approval == '0'"
            type="text"
            v-hasPermi="['sys:site:review']"
            @click="showApprovalDialog(row)"
            >审批</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增多条 场地-->
    <el-dialog
      title="新增场地"
      v-model="createDialogVisible"
      width="75%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="场地图片">
          <el-upload
            :action="actionUrl"
            :headers="myHeaders"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-remove="handleBeforeRemove"
            :on-remove="handleRemove"
            :file-list="imgList"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="场馆名称" prop="stadiumName">
          <el-select
            clearable
            v-model="form.stadiumName"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="searchStadium"
            :loading="stadiumLoading"
            @change="handleStadiumChange"
          >
            <el-option
              v-for="item in stadiumOptions"
              :key="item.id"
              :label="item.stadiumName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="场地类型" prop="type">
          <el-select
            style="width: 100%"
            filterable
            clearable
            v-model="form.type"
            placeholder="场地类型"
            size="small"
          >
            <el-option
              v-for="dict in dict?.type?.site_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-card class="box-card" v-for="(card, index) in cardList" :key="index">
          <template #header>
            <div
              class="clearfix"
              style="display: flex; align-items: center; justify-content: space-between"
            >
              <el-input
                clearable
                v-model="card.siteName"
                placeholder="请输入场地名称"
                class="input-with-label"
              >
                <template #prepend>场地名称</template>
              </el-input>
              <el-button type="primary" style="margin-left: 10px" v-if="index == 0" @click="addCard"
                >+</el-button
              >
              <el-button type="primary" style="margin-left: 10px" @click="delCard(index, card)"
                >-</el-button
              >
            </div>
          </template>
          <div style="padding-bottom: 10px">
            <el-row>
              <el-col :span="8">
                <el-input
                  clearable
                  v-model="card.siteArea"
                  placeholder="请输入场地面积"
                  class="input-with-label"
                >
                  <template #prepend>场地面积</template>
                </el-input>
              </el-col>
              <el-col :span="8">
                <el-input
                  clearable
                  v-model="card.siteLong"
                  placeholder="请输入场地长度"
                  class="input-with-label"
                >
                  <template #prepend>场地长度</template>
                </el-input>
              </el-col>
              <el-col :span="8">
                <el-input
                  clearable
                  v-model="card.siteWide"
                  placeholder="请输入场地宽度"
                  class="input-with-label"
                >
                  <template #prepend>场地宽度</template>
                </el-input>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-input
                  clearable
                  v-model="card.siteSpecification"
                  placeholder="请输入适用规格"
                  class="input-with-label"
                >
                  <template #prepend>适用规格</template>
                </el-input>
              </el-col>
              <el-col :span="8">
                <el-form-item label="场地标准">
                  <el-radio-group
                    :model-value="card.isStandard ?? ''"
                    @update:model-value="
                      (val) => {
                        card.isStandard = val as number
                      }
                    "
                  >
                    <el-radio :label="0">标准场</el-radio>
                    <el-radio :label="1">非标准场</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.type == '1' || form.type == '2'">
                <el-form-item label="场地性质">
                  <el-radio-group
                    :model-value="card.siteNature ?? ''"
                    @update:model-value="
                      (val) => {
                        card.siteNature = val === '' ? null : Number(val)
                      }
                    "
                  >
                    <el-radio :label="0">全场</el-radio>
                    <el-radio :label="1">半场</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-input clearable v-model="card.siteSort">
                  <template #prepend>排序</template>
                </el-input>
              </el-col>
            </el-row>
          </div>
          <el-table :data="card.priceList" border>
            <el-table-column label="价格">
              <template #default="scope">
                <el-input clearable v-model="scope.row.price" size="small" placeholder="价格" />
              </template>
            </el-table-column>
            <el-table-column label="价格备注">
              <template #default="scope">
                <el-input clearable v-model="scope.row.remark" size="small" placeholder="备注" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="90" align="center">
              <template #default="{ $index }">
                <el-button size="small" type="text" @click="addCardTable(index)" v-if="$index == 0"
                  >+
                </el-button>
                <el-button
                  size="small"
                  type="text"
                  @click="delCardTable(index, $index)"
                  v-if="$index > 0"
                  >-
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <template #footer>
        <el-button @click="clickCancel()">取消</el-button>
        <el-button type="primary" @click="creatSiteList">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="编辑场地"
      v-model="editDialogVisible"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="editFormRef" :model="editForm" label-width="80px">
        <el-form-item label="场地类型" prop="stadiumName">
          <el-select
            style="width: 100%"
            filterable
            clearable
            v-model="editForm.type"
            placeholder="场地类型"
            size="small"
          >
            <el-option
              v-for="dict in dict?.type?.site_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="场地名称" prop="stadiumName">
          <el-input clearable v-model="editForm.siteName" />
        </el-form-item>
        <el-form-item label="场地面积" prop="siteArea">
          <el-input clearable v-model="editForm.siteArea" />
        </el-form-item>
        <el-form-item label="场地长度" prop="siteLong">
          <el-input clearable v-model="editForm.siteLong" />
        </el-form-item>
        <el-form-item label="场地宽度" prop="siteWide">
          <el-input clearable v-model="editForm.siteWide" />
        </el-form-item>
        <el-form-item label="场地规格" prop="siteSpecification">
          <el-input clearable v-model="editForm.siteSpecification" />
        </el-form-item>
        <el-form-item label="场地标准" prop="isStandard">
          <el-radio-group v-model="editFormIsStandard">
            <el-radio label="0">是</el-radio>
            <el-radio label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="siteSort">
          <el-input clearable v-model="editForm.siteSort" />
        </el-form-item>
        <el-form-item
          label="场地性质"
          prop="siteNature"
          v-if="editForm.type == '1' || editForm.type == '2'"
        >
          <el-radio-group v-model="editFormSiteNature">
            <el-radio :label="0">全场</el-radio>
            <el-radio :label="1">半场</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-table :data="editForm.priceList" border>
          <el-table-column label="价格">
            <template #default="scope">
              <el-input clearable v-model="scope.row.price" size="small" placeholder="价格" />
            </template>
          </el-table-column>
          <el-table-column label="价格备注">
            <template #default="scope">
              <el-input clearable v-model="scope.row.remark" size="small" placeholder="备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="90" align="center">
            <template #default="{ $index }">
              <el-button size="small" type="text" @click="addEditTable()" v-if="$index == 0"
                >+</el-button
              >
              <el-button size="small" type="text" @click="delEditTable($index)" v-if="$index > 0"
                >-</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm()">确定</el-button>
      </template>
    </el-dialog>

    <!--    // 添加审批对话框-->
    <el-dialog
      title="场地审批"
      v-model="approvalDialogVisible"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form :model="approvalForm" label-width="120px">
        <el-form-item label="场地名称">
          {{ approvalForm.siteName }}
        </el-form-item>
        <el-form-item label="场地类型">
          {{ approvalForm.type === '1' ? '羽毛球' : '篮球' }}
        </el-form-item>
        <el-form-item label="审批状态">
          <el-tag :type="approvalForm.approval === '1' ? 'success' : 'warning'">
            {{
              (approvalForm.approval
                ? { '0': '待审批', '1': '通过', '2': '驳回' }[approvalForm.approval]
                : '') || '未知状态'
            }}
          </el-tag>
        </el-form-item>

        <el-table :data="approvalForm.priceList" border>
          <el-table-column label="价格">
            <template #default="scope">
              <span> {{ scope.row.price }} </span>
            </template>
          </el-table-column>
          <el-table-column label="价格备注">
            <template #default="scope">
              <span> {{ scope.row.remark }} </span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <el-button
          v-if="approvalForm.approval == '0'"
          type="primary"
          @click="handleApprovalAction(1)"
        >
          审批通过
        </el-button>
        <el-button
          v-if="approvalForm.approval == '0'"
          type="danger"
          @click="handleApprovalAction(2)"
        >
          驳回
        </el-button>
        <el-button @click="approvalDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 编辑图片 -->
    <el-dialog
      title="场地图片"
      v-model="picDialogVisble"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="picFormRef" :model="form" label-width="80px">
        <el-form-item label="场地图片">
          <el-upload
            :action="actionUrl"
            :headers="myHeaders"
            list-type="picture-card"
            :on-success="handleOneUploadSuccess"
            :on-error="handleUploadError"
            :before-remove="handleBeforeRemove"
            :on-remove="handleRemove"
            :file-list="imgList"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  updateSite,
  quickSearchStadium,
  createSite,
  getFileBySiteId,
  getPriceBySiteId,
  deletePriceById,
  updateSiteState,
  treeList,
  batchToggleStatus,
  getFileByStadiumIdAndType,
} from '@/api/site/site'
import { createFile, deleteFile } from '@/api/stadium/stadium'
import { useDict } from '@/utils/dict'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type UploadFile,
  type UploadUserFile,
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { ref, reactive, onMounted, computed } from 'vue'
import env from '@/utils/env'

defineOptions({
  name: 'SiteManage',
})

const { dict }: any = useDict({
  dicts: ['site_type'],
})

// Refs
const formRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()
const picFormRef = ref<FormInstance>()

interface QueryParams {
  pageNum: number
  pageSize: number
  searchValue: string
  keyWord?: string
}

interface Form {
  stadiumId: number | null
  stadiumName: string | null
  type: string | null
  id: number | null
}

interface PriceItem {
  id: number | null
  price: string
  remark: string
  siteId: string
}

interface CardItem {
  id: number | null
  siteName: string | null
  siteArea: string | null
  siteLong: string | null
  siteWide: string | null
  siteSpecification: string | null
  isStandard: number | null
  siteNature: number | null
  siteSort: string | null
  priceList: PriceItem[]
}

interface EditForm extends CardItem {
  stadiumId: number | null
  enable: boolean
  type: string | null
}

interface ApprovalForm extends EditForm {
  stadiumName: string | null
  approval: string | null
}

interface StadiumOption {
  id: number
  stadiumName: string
}

// Reactive data
const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  searchValue: '',
})

const form = reactive<Form>({
  stadiumId: null,
  stadiumName: null,
  type: null,
  id: null,
})

const editForm = reactive<EditForm>({
  id: null,
  siteName: null,
  stadiumId: null,
  type: null,
  enable: true,
  siteSort: null,
  siteArea: null,
  siteLong: null,
  siteWide: null,
  siteSpecification: null,
  isStandard: null,
  siteNature: null,
  priceList: [
    {
      id: null,
      price: '',
      remark: '',
      siteId: '',
    },
  ],
})

const approvalForm = reactive<ApprovalForm>({
  id: null,
  siteName: null,
  stadiumId: null,
  stadiumName: null,
  type: null,
  enable: true,
  approval: null,
  siteSort: null,
  siteArea: null,
  siteLong: null,
  siteWide: null,
  siteSpecification: null,
  isStandard: null,
  siteNature: null,
  priceList: [
    {
      id: null,
      price: '',
      remark: '',
      siteId: '',
    },
  ],
})

const picFrom = reactive<Form>({
  stadiumId: null,
  stadiumName: null,
  type: null,
  id: null,
})

const list = ref<any[]>([])
const total = ref<number>(0)
const loading = ref<boolean>(false)
const createDialogVisible = ref<boolean>(false)
const stadiumLoading = ref<boolean>(false)
const stadiumOptions = ref<StadiumOption[]>([])
const approvalDialogVisible = ref<boolean>(false)
const showDetail = ref<boolean>(false)
const picDialogVisble = ref<boolean>(false)
const editDialogVisible = ref<boolean>(false)
const myHeaders = { token: 'u05801#123' }
const imgList = ref<UploadUserFile[]>([])

const cardList = ref<CardItem[]>([
  {
    id: null,
    siteName: null,
    siteArea: null,
    siteLong: null,
    siteWide: null,
    siteSpecification: null,
    isStandard: null,
    siteNature: null,
    siteSort: null,
    priceList: [
      {
        id: null,
        price: '',
        remark: '',
        siteId: '',
      },
    ],
  },
])

// Rules
const rules = {
  stadiumName: [{ required: true, message: '请选择场馆', trigger: 'change' }],
  type: [{ required: true, message: '请选择场地类型', trigger: 'change' }],
}

const actionUrl = env.VITE_APP_BASE_API + '/file/qiniu/upload/img'

// Methods
// 打开 新增Dalog 框
const handleAdd = () => {
  form.stadiumId = null
  form.stadiumName = null
  form.type = null
  imgList.value = []
  cardList.value = []

  cardList.value.push({
    id: null,
    siteName: null,
    siteSort: null,
    siteArea: null,
    siteLong: null,
    siteWide: null,
    siteSpecification: null,
    isStandard: null,
    siteNature: null,
    priceList: [
      {
        id: null,
        price: '',
        remark: '',
        siteId: '',
      },
    ],
  })
  createDialogVisible.value = true
}

//添加卡片
const addCard = () => {
  const newArr: CardItem = {
    id: null,
    siteName: null,
    siteSort: null,
    siteArea: null,
    siteLong: null,
    siteWide: null,
    siteSpecification: null,
    isStandard: null,
    siteNature: null,
    priceList: [
      {
        id: null,
        price: '',
        remark: '',
        siteId: '',
      },
    ],
  }

  cardList.value.push(newArr)
}

//删除卡片
const delCard = (i: number, card: CardItem) => {
  console.log(i)
  console.log(card)
  const delParam = cardList.value[i]
  console.log(delParam)
  if (delParam?.id == null) {
    cardList.value.splice(i, 1)
  } else {
    /* this.$confirm('确定删除该价格吗？操作不可撤销。', '提示', { type: 'warning' }).then(() => {
      if (this.form.id != null) {
        // 调用删除接口
        deletePriceById(delParam.id).then(res => {
          if (res.code == 200) {
            this.$message.success('删除成功')
            this.queryParams.tableData.splice(i, 1)
          }
        })
      } else {
        this.$message.success("删除成功");
      }

    }) */
    cardList.value.splice(i, 1)
  }
}

//新增 框中的添加价格
const addCardTable = (i: number) => {
  // Check if cardList.value[i] exists before accessing its properties
  if (!cardList.value[i]) {
    ElMessage.error('无效的场地索引')
    return
  }

  const newArr: PriceItem = {
    id: null,
    price: '',
    remark: '',
    siteId: '',
  }
  cardList.value[i].priceList.push(newArr)
}

//新增 框中的删除价格
const delCardTable = (cardIndex: number, index: number) => {
  console.log(cardIndex)
  console.log(index)

  // Add safety check to prevent accessing properties of undefined
  if (!cardList.value[cardIndex]) {
    ElMessage.error('无效的场地索引')
    return
  }

  const delParam = cardList.value[cardIndex].priceList[index]
  console.log(delParam)
  cardList.value[cardIndex].priceList.splice(index, 1)
}

const clickCancel = () => {
  createDialogVisible.value = false
  formRef.value?.clearValidate()
}

// 表单提交
const creatSiteList = () => {
  const valid = verificationPrice()
  if (!valid) {
    return
  }
  formRef.value?.validate((valid) => {
    if (valid) {
      const formData = {
        ...form,
        imgList: imgList.value,
        cardList: cardList.value,
      }
      createSite(formData).then((res) => {
        if (res.code == 200) {
          ElMessage.success('操作成功')
          createDialogVisible.value = false
          getList()
        } else {
          ElMessage.error('操作失败')
        }
      })
    }
  })
}

//校验价格
const verificationPrice = (): boolean => {
  // 1. 验证图片
  if (imgList.value.length === 0) {
    ElMessage.error('请上传图片')
    return false
  }

  // 2. 验证第一条场地信息
  const firstCard = cardList.value[0]
  if (!firstCard?.siteName) {
    ElMessage.error('请至少维护一条场地信息')
    return false
  }

  // 3. 验证第一条价格信息
  if (!firstCard?.priceList?.[0]?.price) {
    ElMessage.error('请至少维护一条价格信息')
    return false
  }

  // 4. 验证所有场地信息的必填字段
  for (const item of cardList.value) {
    const requiredFields = [
      { field: 'siteArea', message: '请填写场地面积' },
      { field: 'siteLong', message: '请填写场地长度' },
      { field: 'siteWide', message: '请填写场地宽度' },
      { field: 'isStandard', message: '请选择场地标准' },
      { field: 'siteSort', message: '请输入排序' },
    ]

    // 根据类型决定是否需要验证场地性质
    if (form.type === '1' || form.type === '2') {
      requiredFields.push({
        field: 'siteNature',
        message: '请选择场地性质',
      })
    }

    for (const { field, message } of requiredFields) {
      if ((item as any)[field] == null) {
        // 使用 == 同时检查 null 和 undefined
        ElMessage.error(message)
        return false
      }
    }
  }

  return true
}

// 编辑
const handleEdit = (row: any) => {
  Object.assign(editForm, {
    ...row,
    priceList: [
      {
        id: null,
        price: '',
        remark: '',
        siteId: '',
      },
    ],
  })
  console.log(form)
  editDialogVisible.value = true
  loadDetails(row.id)
}

//  编辑触发的数据加载 获取 价格列表
const loadDetails = (id: string | number) => {
  getPriceBySiteId(id).then((res) => {
    if (res.code == 200 && res.data != null && res.data.length > 0) {
      editForm.priceList = res.data
    }
  })
}

//新增 框中的添加价格
const addEditTable = () => {
  const newArr: PriceItem = {
    id: null,
    price: '',
    remark: '',
    siteId: form.id as unknown as string,
  }
  editForm.priceList.push(newArr)
}

//新增 框中的删除价格
const delEditTable = (index: number) => {
  const delParam = editForm.priceList[index]
  console.log(delParam)
  if (!delParam || delParam.id == null) {
    editForm.priceList.splice(index, 1)
  } else {
    ElMessageBox.confirm('确定删除该价格吗？操作不可撤销。', '提示', {
      type: 'warning',
    })
      .then(() => {
        if (editForm.id != null) {
          // 调用删除接口
          deletePriceById(delParam.id!).then((res) => {
            if (res.code == 200) {
              ElMessage.success('删除成功')
              editForm.priceList.splice(index, 1)
            }
          })
        } else {
          ElMessage.success('删除成功')
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
  }
}

// 提交编辑表单
const submitEditForm = () => {
  console.log()
  if (editForm.siteSort == null) {
    ElMessage.error('请输入排序')
    return
  }
  updateSite(editForm).then((res) => {
    if (res.code == 200) {
      ElMessage.success('操作成功')
      editDialogVisible.value = false
      getList()
    } else ElMessage.error('操作失败')
  })
}

// 打开审批对话框
const showApprovalDialog = (row: any) => {
  console.log(row)
  getPriceBySiteId(row.id).then((res) => {
    if (res.code == 200) {
      Object.assign(approvalForm, {
        ...row,
        priceList: res.data,
      })
      approvalDialogVisible.value = true
    }
  })
  console.log(approvalForm)
}

// 审批切换
const handleApprovalAction = async (type: number) => {
  approvalForm.approval = type.toString()
  try {
    const res = await updateSiteState(approvalForm)
    console.log(res)
    if (res.code == 200) {
      ElMessage.success('操作成功')
      getList()
    } else {
      ElMessage.error('操作失败')
    }
  } catch {
    ElMessage.error('操作失败')
  }
}

// 状态切换
const toggleStatus = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确认${row.enable ? '停用' : '启用'}该场馆？`, '提示')
    if (row.enable == 1) {
      row.enable = 0
    } else {
      row.enable = 1
    }
    const res = await updateSiteState(row)
    console.log(res)
    if (res.code == 200) {
      ElMessage.success('操作成功')
    } else {
      ElMessage.error('操作失败')
    }

    console.log(row.enable)
    getList()
  } catch {
    ElMessage.error('操作失败')
  }
}

// 批量状态切换
const batchToggleStatusFn = async (row: any, type: number) => {
  console.log(row, type)
  row.enable = type
  try {
    await ElMessageBox.confirm(`确认批量${type ? '停用' : '启用'}该场馆？`, '提示')
    const res = await batchToggleStatus(row)
    console.log(res)
    if (res.code == 200) {
      ElMessage.success('操作成功')
    } else {
      ElMessage.error('操作失败')
    }
    getList()
  } catch {
    ElMessage.error('操作失败')
  }
}

// 打开图片编辑对话框
const showPicDialog = (row: any) => {
  console.log(row)
  getFileByStadiumIdAndType(row.stadiumId, { type: row.type }).then((res) => {
    if (res.code == 200) {
      imgList.value = res.data
      picDialogVisble.value = true
      Object.assign(picFrom, {
        ...row,
      })
    }
  })
  console.log(approvalForm)
}

const handleOneUploadSuccess = (res: any, file: UploadFile) => {
  console.log(file)

  // 如果上传成功
  if (res.code == 200) {
    const data = {
      id: null,
      url: res.msg,
      stadiumId: picFrom.stadiumId,
      siteId: null,
      type: '2',
      species: picFrom.type,
    }
    createFile(data).then((res) => {
      if (res.code == 200) {
        ElMessage.success('添加成功')
        // fileList.push(res.data)
      }
    })
  } else {
    ElMessage.error('图片插入失败')
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置表单
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    stadiumName: null,
    type: null,
  })
  getList()
}

const searchStadium = async (query: string) => {
  if (query) {
    stadiumLoading.value = true
    try {
      const res = await quickSearchStadium({ keyword: query })
      stadiumOptions.value = res.data || []
    } finally {
      stadiumLoading.value = false
    }
  } else {
    stadiumOptions.value = []
  }
}

// 选中框值改变时触发
const handleStadiumChange = (selectedId: number) => {
  console.log(selectedId)
  form.stadiumId = selectedId
}

const handleBeforeRemove = async (file: UploadFile) => {
  try {
    await ElMessageBox.confirm('确定删除该图片吗？', '提示', { type: 'warning' })
    const res = await deleteFile(file.uid as unknown as number)
    if (res.code == 200) {
      return true // 允许删除
    }
    return false // 阻止删除
  } catch (error) {
    ElMessage.info('已取消删除')
    return false // 返回false阻止默认删除
  }
}

const handleRemove = (file: UploadFile, fileList: UploadFile[]) => {
  console.log(file)
  for (let index = 0; index < imgList.value.length; index++) {
    if ((imgList.value[index] as UploadUserFile)?.url === (file.response as any).url) {
      imgList.value.splice(index, 1)
      break
    }
  }
  console.log('删除后' + JSON.stringify(imgList.value))
}

const handleUploadSuccess = (res: any, file: UploadFile) => {
  // 如果上传成功
  console.log(res)
  if (res.code == 200) {
    const data = {
      id: null,
      url: res.msg,
      stadiumId: form.stadiumId,
      siteId: form.id as unknown as string,
      type: '2',
      species: form.type,
    }
    imgList.value.push(data as unknown as UploadUserFile)
  } else {
    ElMessage.error('图片插入失败')
  }
}

const handleUploadError = (err: any, file: UploadFile, fileList: UploadFile[]) => {
  ElMessage.error('图片插入失败')
  console.log('图片插入失败' + err)
}

// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    const res = await treeList(queryParams)
    list.value = res.rows
    total.value = res.total
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getList()
})

const editFormSiteNature = computed({
  get: () => editForm.siteNature ?? '',
  set: (value) => {
    editForm.siteNature = value === '' ? null : Number(value)
  },
})

const editFormIsStandard = computed({
  get: () => editForm.isStandard ?? '',
  set: (value) => {
    editForm.isStandard = value === '' ? null : Number(value)
  },
})

const cardSiteNature = (card: CardItem) =>
  computed({
    get: () => card.siteNature ?? '',
    set: (value) => {
      card.siteNature = value === '' ? null : Number(value)
    },
  })
</script>
